//
//  BookListViewController.m
//  Learn
//
//  Created by 迟建国 on 2024/4/2.
//  Copyright © 2024 迟建国. All rights reserved.
//

#import "BookListViewController.h"
#import "BookListCollectionViewCell.h"
#import "BookDetailViewController.h"
#import "HomeRequest.h"

@interface BookListViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UIView *lineView;
@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, strong) NSMutableArray *gradeArr;

@property (nonatomic, assign) NSInteger page;
@property (nonatomic, strong) UIView *topView;
@property (nonatomic, strong) GradeModel *currentGrade;

@end

@implementation BookListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = rgba(229, 229, 229, 1);
    self.page = 1;
    [self setUI];
    [self getGradeList];
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.page = 1;
        [self loadData];
    }];
    self.collectionView.mj_header = header;
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        self.page ++;
        [self loadData];
    }];
    self.collectionView.mj_footer = footer;
    // Do any additional setup after loading the view.
}

- (void)getGradeList {
    [HomeRequest getGradeListWithResult:^(NSMutableArray<GradeModel *> *list) {
        self.gradeArr = list;
        if (list.count != 0) {
            self.currentGrade = self.gradeArr.firstObject;
            dispatch_async(dispatch_get_main_queue(), ^{
                for (int i = 0; i < list.count; i++) {
                    UIButton *titleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
                    titleBtn.tag = 1234567890 + i;
                    [titleBtn setTitle:list[i].gradeName forState:UIControlStateNormal];
                    if (i == 0) {
                        [titleBtn setTitleColor:rgba(12, 183, 108, 1) forState:UIControlStateNormal];
                    } else {
                        [titleBtn setTitleColor:rgba(51, 51, 51, 1) forState:UIControlStateNormal];
                    }
                    titleBtn.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Semibold" size:18];
                    [titleBtn addTarget:self action:@selector(clickedTitle:) forControlEvents:UIControlEventTouchUpInside];
                    [self.topView addSubview:titleBtn];
                    [titleBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                        make.left.equalTo(self.topView.mas_left).offset(SCREEN_W/list.count * i);
                        make.top.equalTo(self.topView.mas_top);
                        make.height.offset(42);
                        make.width.offset(SCREEN_W/list.count);
                    }];
                }
                
                UIView *lineView = [[UIView alloc] init];
                lineView.backgroundColor = rgba(12, 183, 108, 1);
                lineView.layer.cornerRadius = 1.5;
                lineView.layer.masksToBounds = YES;
                [self.view addSubview:lineView];
                self.lineView = lineView;
                [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.top.equalTo(self.view.mas_top).offset(lTopBarHeight + 39);
                    make.left.equalTo(self.view.mas_left).offset(SCREEN_W/list.count/2 - 14);
                    make.width.offset(28);
                    make.height.offset(3);
                }];
            });
            [self loadData];
        }
        
    }];
}

- (void)loadData {
    NSString *type = @"";
    if (self.type == BookTypeHearsay) {
        type = @"听说";
    } else if (self.type == BookTypeHearing) {
        type = @"听力";
    } else if (self.type == BookTypeFollowUpReading) {
        type = @"跟读";
    } else if (self.type == BookTypeWrittenExam) {
        type = @"笔试";
    } else if (self.type == BookTypePhonetic) {
        type = @"音标";
    } else if (self.type == BookTypeModelsp) {
        type = @"典范";
    } else if (self.type == BookTypeNewconcept) {
        type = @"新概念";
    } else if (self.type == BookTypeBlackplum) {
        type = @"黑布林";
    } else if (self.type == BookTypeInterest) {
        type = @"趣味";
    }
    
    [HomeRequest getTextbookListWithGrade:self.currentGrade.grade type:type page:self.page result:^(NSMutableArray<TextbookModel *> *list) {
        [self.collectionView.mj_header endRefreshing];
        [self.collectionView.mj_footer endRefreshing];
        if (self.page == 1) {
            [self.dataArr removeAllObjects];
        }
        [self.dataArr addObjectsFromArray:list];
        [self.collectionView reloadData];
    }];
}
- (void)createRightBarButtonItem
{
    UIButton *button =[[UIButton alloc] initWithFrame:CGRectMake(0, 0, 24, 44)];
    UIImage *img = IMAGENAMED(@"ic_search");
    [button setImage:img forState:UIControlStateNormal];
    [button setImage:img forState:UIControlStateHighlighted];
    button.width = img.size.width;
    [button addTarget:self action:@selector(goSearch) forControlEvents:UIControlEventTouchUpInside];
   
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:button];
    self.navigationItem.rightBarButtonItems =@[item];
}
- (void)setUI {
    UIView *topView = [[UIView alloc] init];
    topView.backgroundColor = UIColor.whiteColor;
    
    [self.view addSubview:topView];
    self.topView = topView;
    [topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.view.mas_top).offset(lTopBarHeight);
        make.height.offset(42);
    }];
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumInteritemSpacing = 10; // 水平间距
    layout.minimumLineSpacing = 15; // 垂直间距
    layout.sectionInset = UIEdgeInsetsMake(15, 10, 15, 10); // 边界间距
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, lTopBarHeight + 43, SCREEN_W, SCREEN_H - SafeAreaBottomHeight - lTopBarHeight - 44) collectionViewLayout:layout];
    collectionView.backgroundColor = [UIColor whiteColor];
    collectionView.delegate = self;
    collectionView.dataSource = self;
    [self.view addSubview:collectionView];
    self.collectionView = collectionView;
    collectionView.showsVerticalScrollIndicator = NO;
    collectionView.showsHorizontalScrollIndicator = NO;
    collectionView.alwaysBounceVertical = YES;
    collectionView.pagingEnabled = NO;
    self.extendedLayoutIncludesOpaqueBars = YES;
    
    [collectionView registerNib:[UINib nibWithNibName:@"BookListCollectionViewCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"BookListCollectionViewCell"];
    if (self.type == BookTypeHearsay)
    {
        topView.backgroundColor = rgba(245, 245, 245, 1);
        self.view.backgroundColor = rgba(245, 245, 245, 1);
        collectionView.backgroundColor = rgba(245, 245, 245, 1);
        [self createRightBarButtonItem];
    }
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    BookListCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"BookListCollectionViewCell" forIndexPath:indexPath];
    if (!cell) {
        cell = [[[NSBundle mainBundle]loadNibNamed:@"BookListCollectionViewCell" owner:self options:nil] lastObject];
    }
    cell.model = self.dataArr[indexPath.row];
    
    if (self.type == BookTypeHearsay)
    {
        [cell setAllCorner:15];
    }
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake((SCREEN_W - 40)/3 - 1, 192);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    TextbookModel *model = self.dataArr[indexPath.row];
    BookDetailViewController *vc = [[BookDetailViewController alloc] init];
    vc.productId = model.productId;
    vc.type = self.type;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - event
- (void)goSearch
{
    if (self.type == BookTypeHearsay) {
        [self pushToViewControllerWithClassName:@"ListenSearchViewController" animated:YES];
    } else {
        [self pushToViewControllerWithClassName:@"ScanViewController" animated:YES];
    }
  
}
- (void)clickedTitle:(UIButton *)sender {
    NSInteger tag = sender.tag - 1234567890;
    self.currentGrade = self.gradeArr[tag];
    [self loadData];
    for (int i = 0; i < self.gradeArr.count; i++) {
        UIButton *btn = [self.view viewWithTag:1234567890 + i];
        [btn setTitleColor:rgba(51, 51, 51, 1) forState:UIControlStateNormal];
    }
    
    [self.lineView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(lTopBarHeight + 39);
        make.left.equalTo(self.view.mas_left).offset(tag * SCREEN_W/self.gradeArr.count + (SCREEN_W/self.gradeArr.count/2 - 14));
        make.width.offset(28);
        make.height.offset(3);
    }];
    [sender setTitleColor:rgba(12, 183, 108, 1) forState:UIControlStateNormal];
}

- (NSMutableArray *)dataArr{
    if (!_dataArr) {
        _dataArr = [NSMutableArray arrayWithCapacity:0];
    }
    return _dataArr;
}
- (NSMutableArray *)gradeArr {
    if (!_gradeArr) {
        _gradeArr = [NSMutableArray arrayWithCapacity:0];
    }
    return _gradeArr;
}
@end
